package com.dzpk.gameserver.net;

import com.dzpk.gameserver.ServerInit;
import com.dzpk.gameserver.util.BeanControler;
import somnus.shutdownhook.AbstractServerShutdownHook;

/**
 * <T>游戏服务器钩子</T>
 * 
 * By Gamer 2013
 */
public class GameServerShutdownHook extends AbstractServerShutdownHook {

    @Override
    public void onShutdown() {

        ServerInit.close();

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        waitForTaskQueueComplete();

        waitForSyncCacheData();

        logger.info("Shutdown gameserver finshed!......");

        // ((ClassPathXmlApplicationContext) BeanControler.getContext()).close();
        // try {
        // if (file != null) {
        // file.delete();
        // }
        // } catch (Exception e) {
        // logger.error("", e);
        // }
    }

    private void waitForSyncCacheData() {
        logger.info("GameStart Waiting Data Save.......!");
        BeanControler.getRoleCache().close();
        logger.info("GameStart Data Save finished.......!");
    }

    private void waitForTaskQueueComplete() {
        logger.info("gameserver Waiting all action execute!");
        // 等待，直到队列中所有任务执行完毕
        long begin = System.currentTimeMillis();
        while (true) {
            // 超过一分钟则退出(解决死锁没法存储问题)
            if (System.currentTimeMillis() - begin > 240 * 1000L) {
                logger.warn("wait all command timeout , give up  these commands ......");
                break;
            }
            if (BeanControler.getTaskQueue().isEmpty()) {
                break;
            } else {
                try {
                    Thread.sleep(1000);
                    logger.info("GameStart Waiting All command execute......");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        logger.info("All Command execute finished!......");
    }
}
